﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Analyst3D;
using ESRI.ArcGIS.Display;
using System.Runtime.InteropServices;
using System.Collections;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.NetworkAnalyst;

namespace SPAS
{
    #region 苏鹏翔、柳伟佳编写
    public partial class LevelForm : Form
    {
        public IMapControl3 mapcontrol;
        public MainForm mainform;

        public LevelForm()
        {
            InitializeComponent();
        }

        private void LevelForm_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = mainform.costAttribut;
        }

        private void levelComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtDistance.Text = ((levelComboBox.SelectedIndex + 1) * 100).ToString();

        }

        private void resetBtn_Click(object sender, EventArgs e)
        {
            mainform.PGC.DeleteAllElements();
            IGPMessages gpMessages = new GPMessagesClass();
            Utils.LoadNANetworkLocations("Stops", mainform.inputFClass, 50, mainform.m_NAContext);
            int Count = mainform.inputFClass.FeatureCount(null);
            //mainform.charu();
            INASolver naSlover = mainform.m_NAContext.Solver;
            try
            {
                naSlover.Solve(mainform.m_NAContext, gpMessages, null);
            }
            catch
            {
                
            }
            mapcontrol.Refresh();
            //mainform.Refresh();
        }

        private void chooseBtn_Click(object sender, EventArgs e)
        {
            mainform.StartAddStopPoint();
            mainform.stationCount = (int)pointCntNumericUpDown.Value;

        }

        private void confirmBtn_Click(object sender, EventArgs e)
        {
            IGPMessages gpMessages = new GPMessagesClass();
            Utils.LoadNANetworkLocations("Stops", mainform.inputFClass, 50, mainform.m_NAContext);
            int Count = mainform.inputFClass.FeatureCount(null);
            //mainform.charu();
            INASolver naSlover = mainform.m_NAContext.Solver;
            try
            {
                naSlover.Solve(mainform.m_NAContext, gpMessages, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + " 重新选点");
                ITable stationTable = mainform.inputFClass as ITable;
                if (stationTable != null)
                {
                    stationTable.DeleteSearchedRows(null);
                    mainform.inputFClass = stationTable as IFeatureClass;
                    mapcontrol.ActiveView.Refresh();
                }
                return;
            }

            //LoadNetDataSet.SetSolverSettings(ref mainform.m_NAContext, comboBox1.SelectedItem.ToString());
            IGeoDataset geoDataset = mainform.m_NAContext.NAClasses.get_ItemByName("Routes") as IGeoDataset;//可以asIFeatureClass
            IFeatureClass route = geoDataset as IFeatureClass;
            if (mainform.stationLayer != null)
            {
                ITable stationTable = mainform.stationLayer.FeatureClass as ITable;
                stationTable.DeleteSearchedRows(null);
                mapcontrol.ActiveView.Refresh();
                //
                stationTable = mainform.inputFClass as ITable;
                stationTable.DeleteSearchedRows(null);
                mainform.inputFClass = stationTable as IFeatureClass;
                mapcontrol.ActiveView.Refresh();
                //mainform.deletallFeature(ref mainform.inputFClass);
                IFeatureLayer stationLayer = mainform.stationLayer;
                //进行标注
                AddGeometry(stationLayer, route);
                mainform.stationLayer = stationLayer;
                mapcontrol.AddLayer(stationLayer);
                mapcontrol.ActiveView.Refresh();
                //mainform.addLayer(ref stationLayer);
            }
            else
            {
                string name = "Station";
                IFeatureLayer stationLayer = Utils.AddFeatureLayer(Utils.GetDefaultGDB() + name, esriGeometryType.esriGeometryPoint);

                ITable stationTable = mainform.inputFClass as ITable;
                stationTable.DeleteSearchedRows(null);
                mainform.inputFClass = stationTable as IFeatureClass;
                
                //进行标注
                AddGeometry(stationLayer, route);
                mainform.stationLayer = stationLayer;
                mapcontrol.AddLayer(stationLayer);
                mapcontrol.ActiveView.Refresh();
                //mainform.addLayer(ref stationLayer);
            }
            //创建点要素图层                     
            IEnvelope envelope = geoDataset.Extent;
            ITable pTable_inputFClass = mainform.inputFClass as ITable;
            pTable_inputFClass.DeleteSearchedRows(null);
            mainform.PGC.DeleteAllElements();
            mapcontrol.ActiveView.Refresh();
        }

        /// <summary>
        /// 向要素图层中添加几何图形
        /// </summary>
        /// <param name="geo"></param>
        /// <param name="layer"></param>
        public void AddGeometry(IFeatureLayer layer, IFeatureClass route)
        {
            // 将要素类转换为dataset
            IDataset myDataset = layer.FeatureClass as IDataset;
            // 获得工作空间
            IWorkspace myWorkspace = myDataset.Workspace;
            // 获得编辑状态
            IWorkspaceEdit wsedit = myWorkspace as IWorkspaceEdit;
            wsedit.StartEditing(true);
            wsedit.StartEditOperation();

            IFeature feature = null;

            int routeCount = route.FeatureCount(null);
            IFeatureClass sourceFeatureClass = layer.FeatureClass;
            double distance = Convert.ToDouble(txtDistance.Text);
            //bool asRation = false; 
            //bool creatPart = false;
            //bool splitHappended = false;
            //int newPartIndex = 0;
            //int newSegementIndex = 0;
            if (wsedit.IsBeingEdited())
            {
                for (int i = 1; i < routeCount + 1; i++)
                {

                    IFeature featuretemp = route.GetFeature(i);
                    IPolyline aroute = route.GetFeature(i).Shape as IPolyline;
                    //double length = aroute.Length * 10E5;
                    double length = aroute.Length;
                    for (double j = 50; j < length; j += distance)
                    {
                        IPoint outPoint = new PointClass();
                        if (j > length)
                        {
                            break;
                        }
                        //ICurve apart=new LineClass();
                        //aroute.QueryPoint(esriSegmentExtension.esriNoExtension, j * 10E-6, false, outPoint);
                        aroute.QueryPoint(esriSegmentExtension.esriNoExtension, j, false, outPoint);
                        feature = sourceFeatureClass.CreateFeature();
                        feature.Shape = outPoint as IGeometry;
                        feature.Store();
                    }
                }
            }

            // 停止编辑
            wsedit.StopEditing(true);
            wsedit.StartEditOperation();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            mainform.IsClose = checkBox1.Checked;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "shapefile（*.shp）|*.shp";
            saveFileDialog1.FileName = "route_export";
            saveFileDialog1.RestoreDirectory = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                saveFileDialog1.AddExtension = true;
                string file = saveFileDialog1.FileName.Substring(0, saveFileDialog1.FileName.LastIndexOf('\\'));
                string name = System.IO.Path.GetFileNameWithoutExtension(saveFileDialog1.FileName);
                if (!System.IO.Directory.Exists(file))
                {
                    System.IO.Directory.CreateDirectory(file);
                }
                try
                {
                    IFeatureClass routesFC;
                    routesFC =  mainform.m_NAContext.NAClasses.get_ItemByName("Routes") as IFeatureClass;
                    Utils.ExportFeature(routesFC, file, name);
                }
                catch
                {
                    MessageBox.Show("导出失败！");
                }
            }
        }
    }
    #endregion
}
